<template>
    <!-- 折叠/展开侧边栏按钮 -->
    <el-button type="primary" :icon="icons" @click="toggleCollapse" />
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="crumbs">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item v-for="item in crumbsPath" :key="item">{{ item }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 深浅色切换开关 -->
    <el-button
      circle
      size="small"
      @click="handleThemeClick"
      ref="themeBtn"
      style="margin-left: 16px; vertical-align: middle;"
      class="theme-btn"
    >
      <el-icon>
        <component :is="isDarkMode ? Sunny : Moon" :style="{ color: isDarkMode ? '#fff' : '#f5e273' }" />
      </el-icon>
    </el-button>
    <div v-if="ripple.show" class="theme-ripple-svg" :style="svgRippleStyle">
      <svg :width="svgSize" :height="svgSize" :style="{ display: 'block' }">
        <defs>
          <clipPath id="wave-clip">
            <path :d="wavePath" />
          </clipPath>
        </defs>
        <circle
          :cx="svgSize/2"
          :cy="svgSize/2"
          :r="svgSize/2"
          :fill="rippleColor"
          clip-path="url(#wave-clip)"
          :opacity="1"
        />
      </svg>
    </div>
    <!-- 头像下拉菜单 -->
    <el-dropdown class="buddha">
        <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        <template #dropdown>
            <el-dropdown-menu>
                <el-dropdown-item @click="isEditHead = true">修改头像</el-dropdown-item>
                <el-dropdown-item divided @click="skip(`/`)">退出登录</el-dropdown-item>
            </el-dropdown-menu>
        </template>
    </el-dropdown>
    <!-- 修改头像弹窗 -->
    <el-dialog v-model="isEditHead" title="修改头像" width="500" align-center>
        <el-upload
            class="upload-demo"
            drag
            action="你的上传接口"
            multiple
            :limit="1"
            accept=".jpg,.png"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
        >
            <el-icon class="el-icon--upload">
                <upload-filled />
            </el-icon>
            <div class="el-upload__text">
                请拖拽上传 或 <em>点击上传</em> 文件
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    注：只能上传 jpg/png 文件，且不超过 500kb
                </div>
            </template>
        </el-upload>
    </el-dialog>
</template>

<script setup>
// 引入 Element Plus 组件
import { ElButton, ElBreadcrumb, ElBreadcrumbItem, ElDropdown, ElDropdownMenu, ElDropdownItem, ElAvatar, ElDialog, ElUpload, ElIcon, ElMessage, ElSwitch } from 'element-plus'
import { Expand, Fold, UploadFilled, Sunny, Moon } from '@element-plus/icons-vue'
import { useDark, useToggle } from '@vueuse/core'
import { ref, computed, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 侧边栏折叠状态
const isCollapse = ref(false)
// 动态切换折叠/展开图标
const icons = computed(() => isCollapse.value ? Expand : Fold)
const route = useRoute()
const router = useRouter()
// 路由路径与中文名映射（只保留实际用到的）
const pathMapping = {
    'admission-policies': '招生政策',
    'campus-lives': '校园生活',
    'issues': '常见问题',
    'majors': '专业信息',
    'scholarships': '奖学金',
    'tuition-fees': '学费信息',
    'qa-histories': '问答历史与统计',
}
let crumbsPath = ref([]) // 面包屑路径
const emit = defineEmits(['getIsCollapse'])
const isEditHead = ref(false) // 控制头像弹窗显示

// 改变侧边栏状态的方法
function toggleCollapse() {
    isCollapse.value = !isCollapse.value
    giveIsCollapse()
}

// 自定义事件，向父组件传递侧边栏状态
const giveIsCollapse = () => {
    emit('getIsCollapse', isCollapse.value)
}

// 监听路由变化，动态生成面包屑
watch(() => route.path, () => {
    const paths = route.path.split('/').filter(item => item && item !== 'home' && item !== 'profile' && isNaN(+item))
    crumbsPath.value = paths.map(path => pathMapping[path] || path)
}, { immediate: true })

// 路由跳转
function skip(path) {
    router.push(path)
}

// 上传成功回调
const handleSuccess = response => {
    isEditHead.value = false
    ElMessage.success('上传成功！')
    console.log('后端返回的数据：', response)
}

// 上传失败回调
const handleError = () => {
    ElMessage.error('上传失败！')
}

// 文件上传前校验
const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt500kb = file.size / 1024 / 1024 < 0.5

    if (!isJpgOrPng) {
        ElMessage.error('只能上传 JPG 或 PNG 文件')
        return false
    }
    if (!isLt500kb) {
        ElMessage.error('文件大小不能超过 500kb')
        return false
    }
    return true
}

// 超出文件数限制回调
const handleExceed = () => {
    ElMessage.warning('超出文件数限制，最多只能上传一个文件')
}

// 文件移除回调
const handleRemove = () => {
    ElMessage.info('文件已移除')
}

const isDark = useDark()
const toggleDark = useToggle(isDark)
const isDarkMode = ref(localStorage.getItem('isDarkMode') === 'true' ? true : isDark.value)

function toggleTheme() {
  isDarkMode.value = !isDarkMode.value
}

watch(isDarkMode, val => {
  toggleDark(val)
  localStorage.setItem('isDarkMode', val)
}, { immediate: true })

const themeBtn = ref(null)
const ripple = ref({ show: false, x: 0, y: 0, color: '', key: 0 })

function handleThemeClick() {
  // 1. 计算按钮中心在视口的位置
  const btn = themeBtn.value.$el || themeBtn.value
  const rect = btn.getBoundingClientRect()
  const x = rect.left + rect.width / 2
  const y = rect.top + rect.height / 2

  // 2. 触发扩散
  ripple.value = {
    show: false, x: 0, y: 0, color: '', key: Date.now()
  }
  nextTick(() => {
    ripple.value = {
      show: true,
      x, y,
      color: '', // 颜色已在rippleStyle里动态判断
      key: Date.now()
    }
  })

  // 3. 动画后再切换主题
  setTimeout(() => {
    isDarkMode.value = !isDarkMode.value
    ripple.value.show = false
  }, 700)
}

const svgSize = 2 * Math.max(window.innerWidth, window.innerHeight)
const waveAmplitude = 32 // 波浪幅度
const waveCount = 8 // 波浪个数

const wavePath = computed(() => {
  const r = svgSize / 2
  let d = ''
  for (let i = 0; i <= 360; i += 2) {
    const rad = (i * Math.PI) / 180
    const wave = Math.sin(rad * waveCount) * waveAmplitude
    const x = r + (r + wave) * Math.cos(rad)
    const y = r + (r + wave) * Math.sin(rad)
    d += i === 0 ? `M${x},${y}` : `L${x},${y}`
  }
  d += 'Z'
  return d
})

const svgRippleStyle = computed(() => {
  if (!ripple.value.show) return { display: 'none' }
  return {
    position: 'fixed',
    left: `${ripple.value.x - svgSize/2}px`,
    top: `${ripple.value.y - svgSize/2}px`,
    width: `${svgSize}px`,
    height: `${svgSize}px`,
    pointerEvents: 'none',
    zIndex: 99999,
    transform: 'scale(0)',
    opacity: 1,
    animation: 'theme-svg-ripple 1.5s cubic-bezier(.4,0,.2,1) forwards'
  }
})

const rippleColor = computed(() => {
  const nextIsDark = !isDarkMode.value
  return nextIsDark ? '#222' : '#fff'
})
</script>

<style>
.crumbs {
    margin-left: 1%;
}

.buddha {
    position: absolute;
    right: 1%;
    cursor: pointer;
}

.theme-btn {
    position: absolute;
    right: 5vw;
    cursor: pointer;
}

@keyframes theme-svg-ripple {
  to {
    transform: scale(1.2);
    opacity: 0;
  }
}
.theme-ripple-svg {
  will-change: transform, opacity;
  z-index: 99999 !important;
  pointer-events: none;
}
</style>